import {
  colorLighted,
  colorDarken,
  colorHexToRgb,
  colorRgbToHex,
  colorBrightnessEstimate,
} from '@vimi/utils-tool'

export const getPropertyColor = (prop = 'primary') =>
  window.getComputedStyle(document.body).getPropertyValue(`--${prop}`).toUpperCase()

export const setTheme = (color, themeLocal) => {
  const currentColor = getPropertyColor()

  if (!color || (currentColor && color.toUpperCase() === currentColor)) {
    return
  }

  const setProperty = (property, value) => {
    document.documentElement.style.setProperty(property, value)
  }

  setProperty('--primary', color)

  if (themeLocal) {
    localStorage.setItem(themeLocal, color)
  }

  const [red, green, blue] = colorHexToRgb(color)

  const isPrimaryLight = colorBrightnessEstimate(red, green, blue)
  setProperty('--primary-text', isPrimaryLight ? '#333' : '#fff')

  const lights = getLightCluster(red, green, blue)
  for (const [i, light] of lights.entries()) {
    setProperty(`--primary-light-${i + 1}`, colorRgbToHex(...light))
  }

  const darks = getDarkCluster(red, green, blue)
  for (const [j, dark] of darks.entries()) {
    setProperty(`--primary-dark-${j + 1}`, colorRgbToHex(...dark))
  }

  const trans = getTransparentCluster(red, green, blue)
  for (const [k, tran] of trans.entries()) {
    setProperty(`--primary-transparent-${k + 1}`, tran)
  }
  setProperty('--primary-transparent-0', `rgba(${red},${green},${blue}, 0.02)`)
}

export const getLightCluster = (red, green, blue) => {
  const clusters = []
  for (let i = 1; i <= 9; i++) {
    clusters.push(colorLighted(red, green, blue, Number((i / 10).toFixed(2))))
  }
  return clusters
}

export const getDarkCluster = (red, green, blue) => {
  const clusters = []
  for (let i = 1; i <= 9; i++) {
    clusters.push(colorDarken(red, green, blue, Number((i / 10).toFixed(2))))
  }
  return clusters
}

export const getTransparentCluster = (red, green, blue) => {
  const clusters = []
  const rgb = `${red},${green},${blue}`
  for (let i = 1; i <= 9; i++) {
    clusters.push(`rgba(${rgb}, ${Number((i / 10).toFixed(2))})`)
  }
  return clusters
}
